import axios from "axios";
import type { AxiosInstance, AxiosResponse } from "axios";
import type { IAxiosConfig } from "./type";

class HJRequest {
  instance: AxiosInstance;
  constructor(config: IAxiosConfig) {
    this.instance = axios.create({
      baseURL: config.baseURL,
      timeout: config.timeout,
    });
    this.instance.interceptors.request.use(
      config.interceptors?.requestInterceptor as any,
      config.interceptors?.requestInterceptorError
    );
    this.instance.interceptors.response.use(
      config.interceptors?.responseInterceptor,
      config.interceptors?.responseInterceptorError
    );
  }
  // 网络请求
  request<T = AxiosResponse>(config: IAxiosConfig<T>) {
    return new Promise<T>((resolve, reject) => {
      config.interceptors?.requestInterceptor &&
        (config = config.interceptors?.requestInterceptor(config));
      this.instance
        .request<any, T>({
          ...config,
        })
        .then((res: any) => {
          config.interceptors?.responseInterceptor &&
            (res = config.interceptors?.responseInterceptor(res));
          // resolve(res as any as T);
          resolve(res.data);
        })
        .catch((err) => reject(err));
    });
  }
  get<T = AxiosResponse>(config: IAxiosConfig<T>) {
    return this.request<T>({ ...config, method: "GET" });
  }
  post<T = AxiosResponse>(config: IAxiosConfig<T>) {
    return this.request<T>({ ...config, method: "POST" });
  }
  patch<T = AxiosResponse>(config: IAxiosConfig<T>) {
    return this.request<T>({ ...config, method: "PATCH" });
  }
  delete<T = AxiosResponse>(config: IAxiosConfig<T>) {
    return this.request<T>({ ...config, method: "DELETE" });
  }
}

export default HJRequest;
